package admin

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"go_my_framework/app/global/request"
	"go_my_framework/app/service"
	"go_my_framework/util/base"
	"html/template"
	"strconv"
)

// 权限列表
func PurviewIndex(c *gin.Context) {
	svc := service.PurviewService{}
	list := svc.GetAll(make([]int, 0))
	jsonList, _ := json.Marshal(list)
	base.Html(c, "/admin/purview/index", gin.H{"list": string(jsonList)})
}

// 添加权限
func PurviewAdd(c *gin.Context) {
	if c.Request.Method == "POST" {
		var f request.PurviewAddForm
		if err := c.ShouldBind(&f); err != nil {
			base.Error(c, err.Error(), nil)
			return
		}
		svc := service.PurviewService{}
		err := svc.AddPurview(f.Name, f.Pid, f.Url, f.IsShow, f.Sort, f.Icon)
		if err != nil {
			base.Error(c, err.Error(), nil)
			return
		} else {
			base.Success(c, "添加成功", nil)
			return
		}
	} else {
		svc := service.PurviewService{}
		treeHtml := svc.GetPurviewTree(0)
		base.Html(c, "/admin/purview/add", gin.H{"treeHtml": template.HTML(treeHtml)})
	}
}

// 编辑权限
func PurviewEdit(c *gin.Context) {
	if c.Request.Method == "POST" {
		var f request.PurviewAddForm
		if err := c.ShouldBind(&f); err != nil {
			base.Error(c, err.Error(), nil)
			return
		}
		idStr := c.PostForm("id")
		id, _ := strconv.Atoi(idStr)
		svc := service.PurviewService{}
		err := svc.EditPurview(id, f.Name, f.Pid, f.Url, f.IsShow, f.Sort, f.Icon)
		if err != nil {
			base.Error(c, err.Error(), nil)
			return
		} else {
			base.Success(c, "提交成功", nil)
			return
		}
	} else {
		idStr := c.Query("id")
		id, _ := strconv.Atoi(idStr)
		svc := service.PurviewService{}
		data, err := svc.GetRow(id)
		if err != nil {
			base.Error(c, err.Error(), nil)
			return
		}

		treeHtml := svc.GetPurviewTree(data.Pid)
		base.Html(c, "purview/edit", gin.H{"data": data, "treeHtml": template.HTML(treeHtml)})
	}
}

// 删除权限
func PurviewDel(c *gin.Context) {
	idStr := c.PostForm("id")
	id, _ := strconv.Atoi(idStr)
	svc := service.PurviewService{}
	err := svc.DelRow(id)
	if err != nil {
		base.Error(c, err.Error(), nil)
		return
	} else {
		base.Success(c, "已删除", nil)
		return
	}
}